import { NameSpace } from 'utils/index';
import { Message } from '@teamix/ui';

import exceed from 'utils/apimap';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;

const ns = NameSpace('mirrorsync');
export const RECEIVE_MiRROR_SETTINGS = ns('RECEIVE_MiRROR_SETTINGS');
export const RECEIVE_MiRROR_LIST = ns('RECEIVE_MiRROR_LIST');
export const RECEIVE_MiRROR_STATUS = ns('RECEIVE_MiRROR_STATUS');
export const RECEIVE_LAST_MiRROR_RECORD = ns('RECEIVE_LAST_MiRROR_RECORD');
export const RECEIVE_WEBHOOKS = ns('RECEIVE_WEBHOOKS');
export const CREATE_WEBHOOK = ns('CREATE_WEBHOOK');
export const REMOVE_WEBHOOK = ns('REMOVE_WEBHOOK');
export const TEST_RESULT = ns('TEST_RESULT');
export const UPDATE_DATA = ns('UPDATE_DATA');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

// 查询仓库同步设置
export function getMirrorSync() {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'project.mirror.settings',
        params: {
          projectId: pathResource.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_MiRROR_SETTINGS,
          data: result,
        });
      });
  };
}

// 更新仓库同步设置
export function updateMirrorSync(data, success) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data: {
        isLoadingSyncStatus: true,
      },
    });

    exceed
      .fetch({
        api: 'project.mirror.settings.put',
        params: {
          projectId: pathResource.id,
        },

        data,
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_MiRROR_SETTINGS,
          data: result,
        });

        success && success();
      });
  };
}

// 解除仓库同步授权设置
export function unbindMirrorAuthorizedSettings(cb) {
  return () => {
    exceed
      .fetch({
        api: 'project.mirror.settings.authorized.put',
        params: {
          projectId: pathResource.id,
        },
      })
      .then((result) => {
        cb && cb(result.result);
      });
  };
}

// 查询仓库同步历史记录列表
export function getMirrorSyncList(page, per_page) {
  return (dispatch, getState) => {
    const state = getState().project.projectSettings.mirror;
    const { pageSize = 10 } = state;
    exceed
      .forceFetch({
        api: 'project.mirror.sync_records',
        params: {
          projectId: pathResource.id,
        },

        data: {
          page,
          per_page: per_page || pageSize,
          order_by: 'gmt_modified',
          sort: 'desc',
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_MiRROR_LIST,
          data: result,
        });
      });
  };
}

export function mirrorSync(polling, error = null) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'project.mirror',
        params: {
          projectId: pathResource.id,
        },
      })
      .then((result) => {
        if (result.result === true) {
          dispatch({
            type: RECEIVE_MiRROR_STATUS,
            data: result.result,
          });

          dispatch(getMirrorSyncList(1));
          polling();
        } else {
          error && error();
        }
      });
  };
}

export function getLastMirrorSyncRecord(clear = null, onSync = null) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'project.mirror.last_mirror_sync_record',
        params: {
          projectId: pathResource.id,
        },
      })
      .then((result) => {
        if (result.sync_status !== 'READY' && result.sync_status !== 'SYNCHRONIZING') {
          clear && clear(result);
        } else {
          onSync && onSync(result);
        }
        dispatch({
          type: RECEIVE_LAST_MiRROR_RECORD,
          data: result,
        });
      })
      .catch((error) => {
        console.error(error);
      });
  };
}

// 查询webhooks列表
export function getWebhooks() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'project.web_hooks',
        params: {
          projectId: pathResource.id,
        },

        data: {
          per_page: 100,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_WEBHOOKS,
          data: result.list.sort((a, b) => a.type - b.type),
        });
      });
  };
}

// 新建webhook
export function create(formData, cb) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'project.web_hooks.add',
        params: {
          projectId: pathResource.id,
        },

        data: formData,
      })
      .then((result) => {
        setTimeout(() => {
          Message.success({
            title: intl.get({
              id: 'code-assets.settingsMirrorSync.actions.WebhookCreated',
              defaultMessage: 'Webhook 新建成功',
            }),
          });
        }, 500);
        dispatch({
          type: CREATE_WEBHOOK,
          data: result,
        });

        cb && cb();
      })
      .fail(() => {
        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };
}

// 测试webhook
export function testHook(hookId, cb) {
  return (dispatch, getState) => {
    const state = getState().project.projectSettings.settingsWebhooks;
    const { webhooks } = state;
    const hookTestResult = webhooks.find((item) => item.id === hookId);

    exceed
      .fetch({
        api: 'project.web_hooks.test',
        params: {
          projectId: pathResource.id,
          webhookId: hookId,
        },
      })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.settingsMirrorSync.actions.WebhookTestSucceeded',
            defaultMessage: 'Webhook 测试成功',
          }),
          duration: 2000,
        });

        hookTestResult.last_test_result = 'ok';
        dispatch({
          type: TEST_RESULT,
          data: [...webhooks],
        });

        cb && cb();
      })
      .fail(() => {
        hookTestResult.last_test_result = 'error';
        dispatch({
          type: TEST_RESULT,
          data: [...webhooks],
        });

        cb && cb();
      });
  };
}

// 删除webhook
export function remove(hookId, cb) {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'project.web_hooks.delete',
        params: {
          projectId: pathResource.id,
          webhookId: hookId,
        },
      })
      .then(() => {
        setTimeout(() => {
          Message.success({
            title: intl.get({
              id: 'code-assets.settingsMirrorSync.actions.WebhookDeleted',
              defaultMessage: 'Webhook 删除成功',
            }),
          });
        }, 500);
        dispatch({
          type: REMOVE_WEBHOOK,
          data: hookId,
        });

        cb && cb();
      });
  };
}

// 查询某一条webhook
export function getOneHook(hookId, cb) {
  return () => {
    exceed
      .forceFetch({
        api: 'project.web_hooks.get',
        params: {
          projectId: pathResource.id,
          webhookId: hookId,
        },
      })
      .then((result) => {
        cb(result);
      });
  };
}

// 编辑webhook
export function edit(hookId, formData, cb) {
  return (dispatch, getState) => {
    const state = getState().project.projectSettings.settingsWebhooks;
    const { webhooks } = state;

    exceed
      .fetch({
        api: 'project.web_hooks.edit',
        params: {
          projectId: pathResource.id,
          webhookId: hookId,
        },

        data: formData,
      })
      .then((result) => {
        setTimeout(() => {
          Message.success({
            title: intl.get({
              id: 'code-assets.settingsMirrorSync.actions.WebhookUpdated',
              defaultMessage: 'Webhook 更新成功',
            }),
          });
        }, 500);
        const hook = webhooks.map((element) => {
          if (element.id === hookId) {
            element = result;
          }
          return element;
        });
        dispatch({
          type: RECEIVE_WEBHOOKS,
          data: hook,
        });

        cb && cb();
      })
      .fail(() => {
        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };
}
